package com.goods.controller.business;

import com.goods.business.service.HealthService;
import com.goods.common.model.business.Health;
import com.goods.common.model.system.User;
import com.goods.common.response.ResponseBean;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.system.UserInfoVO;
import com.goods.system.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/business/health")
public class HealthController {

    @Autowired
    private HealthService healthService;

    @Autowired
    private UserService userService;

    ///business/health/report
    @SneakyThrows
    @PostMapping("/report")
    public ResponseBean report(@RequestBody Health health) {

        //查询登录用户信息
        UserInfoVO info = userService.info();
        System.out.println("info = " + info);
        //根据登录用户用户名获取userId
        User user = userService.findUserByName(info.getUsername());
        Long userId = user.getId();
        System.out.println("userId = " + userId);

        //判断用户是否已经打卡
        Boolean report = healthService.report(health, userId);
        //如果用户未打卡，进行打卡并返回true，返回到前端打卡成功，如果用户返回未成功打卡的信息
        if (report) {
            return ResponseBean.success();
        }else {
            String msg="今天已经打过卡";
            Map<String, Object> errorReturnMap = new HashMap<>();
            errorReturnMap.put("msg",msg);
            return ResponseBean.error(errorReturnMap);
        }


    }

    ///business/health/isReport
    @SneakyThrows
    @GetMapping("/isReport")
    public ResponseBean isReport(){
        //查询登录用户信息
        UserInfoVO info = userService.info();
        //根据登录用户用户名查询用户对象
        User user = userService.findUserByName(info.getUsername());
        //获取userId
        Long userId = user.getId();
        //进行查询是否打卡操作
        Health health = healthService.isReport(userId);
        //返回结果
        return ResponseBean.success(health);
    }

    ///business/health/history?pageSize=4&pageNum=1
    @SneakyThrows
    @GetMapping("/history")
    public ResponseBean history(Integer pageSize, Integer pageNum){

        //查询登录用户信息
        UserInfoVO info = userService.info();
        //根据登录用户用户名查询用户对象
        User user = userService.findUserByName(info.getUsername());
        //获取userId
        Long userId = user.getId();

        //根据userId查询用户打卡信息
        List<Health> healthList = healthService.history(userId);
        //进行分页
        List<Health> item = ListPageUtils.page(healthList, pageSize, pageNum);

        //封装结果
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("rows",item);
        returnMap.put("total", item.size());

        //返回结果到前端
        return ResponseBean.success(returnMap);

    }
}
